package com.core.thread;

import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import com.core.interfaces.IMessageExecutorPool;
import com.core.interfaces.IScheduledThread;

public abstract class BaseMessageExecutorPool implements IMessageExecutorPool {

	/**线程map**/
	protected Map<String, IScheduledThread> threadMap = new ConcurrentHashMap<String, IScheduledThread>();
	
	/**线程池列表**/
	protected List<IScheduledThread> threadList = new Vector<IScheduledThread>();
	
	/** 执行器当前所在位置 **/
	protected AtomicInteger autoExecutorIndex = new AtomicInteger(0);
	

	@Override
	public void shutDown()
	{
		if(threadList==null)
			return;
		for(IScheduledThread thread:threadList)
		{
			thread.shutDown();
		}
	}
	
	
	/**
	 * 增加一个线程
	 * @return
	 */
	public IScheduledThread addThreadPoolExecutor()
	{
		IScheduledThread executor = new ScheduledThread();
		executor.init();
		if(threadMap.containsKey(executor.getThreadName())){
			Thread.dumpStack();
		}
		threadMap.put(executor.getThreadName(), executor);
		threadList.add(executor);
		return executor;
	}
	
	/**
	 * 获取随即线程池
	 * @return
	 */
	public IScheduledThread getIndexExecutor() 
	{
		return threadList.get(autoExecutorIndex.getAndAdd(1)%threadList.size());
	}
	

	@Override
	public IScheduledThread getExecutor(String threadName)
	{
		return threadMap.get(threadName);
	}
}
